#include "listTable.h"



void printElems(listNode* L)
{
    int index = 1;
    listNode *travel;
    travel = L->next;
    printf("content:[.");
    while(travel)
    {
        printf("index: %d,data:%d|.",index,travel->data,travel);
        travel = travel->next;
        index++;
    }
    printf("].\n.");
}

int initList(listNode* L)
{
    L->data = 1;
    L->next = (listNode*)malloc(sizeof(listNode));
    L->next->next = NULL;
}

int createListPre(listNode* L,ElemType *data,int length)
{
    listNode *travel,*front;
    front = L;
    int index = 0;
    while(index < length)
    {
        travel = (listNode*)malloc(sizeof(listNode));
        travel->data = data[index];
        travel->next = front->next;
        front->next = travel;
        index++;
    }

    return 1;
}


int createTableBack(listNode* L,ElemType *data,int length)
{
    listNode *travel,*rear;
    rear = L->next;
    int index = 0;
    while(index < length)
    {
        travel = (listNode*)malloc(sizeof(listNode));
        travel->data = data[index];
        rear->next = travel;
        rear = travel;
        index++;
    }

    return 1;
}

void clearTable(listNode* L)
{
    listNode *travel,*tmp;
    travel = L->next;
    while(travel)
    {
        tmp = travel;
        travel = travel->next;
        free(tmp);
    }
}

int tableLength(listNode* L)
{
    int count = 0;
    listNode *travel;
    travel = L->next;
    while(travel)
    {
        count++;
    }
    return count;
}

int tableEmpty(listNode* L)
{
    if(tableLength(L) == 0)
        return 1;
    else
        return 0;
}

int getElem(listNode* L,int index,ElemType *data)
{
    int num = 1;
    listNode *travel;
    travel = L->next;
    while(travel && (num < index))
    {
        travel = travel->next;
        num++;
    }

    if(index < 0|| num < index)
        return -1;

    *data = L->data;
    return 1;
}

int locateElem(listNode* L,ElemType data)
{
    int num = 1;
    listNode *travel,*tmp;
    travel = L->next;
    while(travel)
    {
        if(data == travel->data)
            return num;
        travel = travel->next;
        num++;
    }

    return -1;
}

int insertElem(listNode* L,int index, ElemType data)
{
    int num = 1;
    listNode *travel,*tmp;
    travel = L->next;
    while(travel && (num < index))
    {
        travel = travel->next;
        num++;
    }

    if(index < 0|| num < index)
        return -1;

    tmp = (listNode*)malloc(sizeof(listNode));
    tmp->data = data;
    tmp->next = travel->next;
    travel->next = tmp;
    return 1;
}


int deleteElem(listNode* L,int index, ElemType *data)
{
    int num = 1;
    listNode *travel,*tmp;
    travel = L->next;
    while(travel && (num < index))
    {
        travel = travel->next;
        num++;
    }

    if(index < 0|| num < index)
        return -1;
    tmp = travel->next;
    *data = travel->data;
    travel->next = tmp->next;
    free(tmp);
    return 1;
}